import i18n from '@/lang'
import axios from 'axios'
import { message as AMessage, Modal } from 'ant-design-vue'
import { __getLocal } from '@/utils/tools.js'
import { useAccountStore } from '@/stores/account'

const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL + import.meta.env.VITE_APP_BASE_API,
  responseType: 'json',
  validateStatus(status) {
    return status === 200
  }
})

// Request interceptors
/**
 * @param NoPostSeqNo 参数是否带公共参数 seqNo,在api方法传递参数，exam:account.js fetchSeqNo()
 * @param {showSignErrorMessage} boolean 是否跳过同一封装的报错信息,显示签名验证失败弹框
 */
let showSignErrorMessage = false
service.interceptors.request.use(
  (config) => {
    if (config.meta && Object.keys(config.meta).length > 0) {
      Object.keys(config.meta).forEach((key) => {
        config.headers[key] = config.meta[key]
      })
    }
    const accountStore = useAccountStore()
    showSignErrorMessage = !!config?.otherConfigs?.showSignErrorMessage
    let language = i18n.global.locale.value || 'zh'
    config.headers.language = language
    config.headers.tenant = 'MDAwMA=='
    config.headers.token = `Bearer ${accountStore.TOKEN}`
    config.headers.Authorization = `Basic aW5zdXJlX3dlYjppbnN1cmVfd2ViX3NlY3JldA==`
    return config
  },
  (error) => {
    Promise.reject(error)
  }
)

// Response interceptors
const LOGIN_EXPIRED_CODE = [40000, 40001, 40002, 40003, 40005, 40006, 40008, 40009] // Java 登录过期code
function showModalWarn(message) {
  const accountStore = useAccountStore()
  Modal.warning({
    keyboard: false,
    title: i18n.global.t('axios.remind'),
    okText: i18n.global.t('axios.confirm'),
    content: message,
    onOk() {
      accountStore.resetToken()
      window.location.href = import.meta.env.VITE_INSURED_LOGIN_URL
    }
  })
}
function handleBlobResult(res) {
  // 处理blob返回结果
  // TODO 临时处理blob报错，后续需要系统处理
  return new Promise((resolve, reject) => {
    let blob = new Blob([res.data], {
      type: 'application/octet-stream'
    })
    const fileReader = new FileReader()
    fileReader.readAsText(blob, 'utf-8')
    fileReader.onload = function () {
      try {
        const msg = JSON.parse(fileReader.result)
        AMessage.error(i18n.global.locale.value === 'zh' ? msg.msg : msg.msg_en)
        resolve(false)
      } catch {
        resolve(true)
      }
    }
  })
}
service.interceptors.response.use(
  async (response) => {
    const resData = response.data
    if (response.config.responseType === 'blob') {
      const canDownLoad = await handleBlobResult(response)
      return canDownLoad ? response : null
    }
    if (resData.isSuccess) {
      return resData
    }
    if (resData.isSuccess === false) {
      const message =
        i18n.global.locale.value === 'zh'
          ? resData.msg
          : resData.msg_en
            ? resData.msg_en
            : resData.msg
      if (LOGIN_EXPIRED_CODE.includes(resData.code)) {
        showModalWarn(message)
      } else {
        if (showSignErrorMessage) {
          showModalWarn('当前用户无账号，是否跳转至登录页面')
        } else {
          AMessage.error(message || '未知错误')
        }
        return Promise.reject(response.data)
      }
    }
  },
  async (error) => {
    console.log('error', error)
    const code = error?.response?.data?.code || error?.response?.status
    const isExpirdToken = LOGIN_EXPIRED_CODE.includes(code)
    if (error?.response?.config?.responseType === 'blob') {
      if (error?.response?.status == '401') {
        // blob格式无法获取message,手动配置,中英文配置需额外处理。
        showModalWarn('会话超时，请重新登录')
        return Promise.reject(error)
      }
    }
    console.log('isExpirdToken', isExpirdToken)
    const message =
      error?.response?.data?.msg || error?.response?.data.error || error.message || '未知错误'
    if (showSignErrorMessage || isExpirdToken) {
      showModalWarn(message)
    } else {
      AMessage.error(message)
    }
    return Promise.reject(error)
  }
)

export default service
